package org.neptune.service.schedule;

import java.util.Date;
import java.util.List;

import org.neptune.api.entity.SeckillOrderWaitPay;
import org.neptune.api.entity.SeckillOrderWaitPayExample;
import org.neptune.common.constant.NeptuneConstant;
import org.neptune.common.util.DateUtil;
import org.neptune.service.config.NeptuneConfig;
import org.neptune.service.dao.SeckillOrderWaitPayMapper;
import org.neptune.service.redis.RedisRepository;
import org.neptune.service.redis.RedissonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @author lwl
 * @date 2020/4/1 15:06
 */
@Component
public class SeckillOrderWaitPaySchedule {

	@Autowired
	private SeckillOrderWaitPayMapper seckillOrderWaitPayMapper;

	@Autowired
	private RedisRepository redisRepository;

	@Autowired
	private NeptuneConfig neptuneConfig;

	@Scheduled(cron = "0 1 0 * * ?")
	public void deleteTimeoutOrder() {
		SeckillOrderWaitPayExample example = new SeckillOrderWaitPayExample();
		Date date = DateUtil.getSecond(-neptuneConfig.seckillCacheTimePay);
		example.createCriteria().andCreateTimeLessThan(date);
		List<SeckillOrderWaitPay> seckillOrderWaitPays = seckillOrderWaitPayMapper
				.selectByExample(example);

		for (SeckillOrderWaitPay seckillOrderWaitPay : seckillOrderWaitPays){
			String countKey = RedissonUtil.getRedisKey(NeptuneConstant.REDIS_SECKILL_GOODS_COUNT,
					seckillOrderWaitPay.getSeckillId());
			SeckillOrderWaitPayExample temp = new SeckillOrderWaitPayExample();
			temp.createCriteria().andUserIdEqualTo(seckillOrderWaitPay.getUserId())
					.andSeckillIdEqualTo(seckillOrderWaitPay.getSeckillId());
			seckillOrderWaitPayMapper.deleteByExample(temp);
			redisRepository.increment(countKey, neptuneConfig.seckillInfoCacheTime);
		}
	}

}
